<template>
  <div>
    <a-modal v-if="!(role === 'root')" v-model:open="open" title="Basic Modal" @ok="handleModalOk">
      <p>您确定接收邀请吗</p>
    </a-modal>
    <el-button @click="sendPeopleClick">A给B发</el-button>
    <el-button @click="receivePeopleClick">B给A发</el-button>
    <a-button @click="screenShareClick">开始共享</a-button>
    <div :style="{ background: '#fff', padding: '24px', height: '80%' }">
      <div>
        <video ref="video" autoplay class="h-100 w-auto" controls muted />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted, watchEffect } from 'vue';
import { UseSocketStore } from "@/stores/index";
import { useDisplayMedia, useDevicesList } from '@vueuse/core';
import { useRouter } from 'vue-router';

let router = useRouter();
const role = router.currentRoute.value.query.role;
const { stream, start } = useDisplayMedia();
const video = ref(null);
const store = UseSocketStore();
const roomId = 'WEB-RTC-01';
const open = ref(false);
let peer = ref(null);
let localStream = ref(null);

watch(stream, (newStream, oldStream) => {
  console.log(newStream);
  if (video.value && newStream) {
    video.value.srcObject = newStream;
    store.screenStream = newStream;
  }
});

watchEffect(() => {
  store.socket?.on('callRemote', (msg) => {
    console.log('监听到后端发起请求', msg);
    if (msg) {
      open.value = true;
    }
  });

  store.socket?.on('acceptCall', (msg) => {
    console.log('监听到后端发同意请求', msg);
    if (role === 'root') {


    }
  });

  store.socket?.on('sendOffer', async ({ offer }) => {
    console.log('收到offer', offer);

    peer.value = new RTCPeerConnection();
    localStream.value = await getLocalStream();

    const localStreamValue = localStream.value;
    if (localStreamValue) {
      localStreamValue.getTracks().forEach(track => {
        peer.value.addTrack(track, localStreamValue);
      });
    } else {
      console.error('无法获取本地流');
    }

    await peer.value.setRemoteDescription(offer);

    const answer = await peer.value.createAnswer();
    console.log('answer', answer);

    await peer.value.setLocalDescription(answer);

    store.socket.emit('sendAnswer', { answer, roomId });
  });

  store.socket?.on('sendAnswer', async ({ answer }) => {
    console.log('收到answer', answer);

    if (peer.value && peer.value.signalingState === 'have-remote-offer') {
      try {
        await peer.value.setRemoteDescription(answer);
      } catch (error) {
        console.error('Failed to set remote answer sdp:', error);
      }
    } else {
      console.error('RTCPeerConnection is not in the correct state to set remote description');
    }
  });
});

const sendPeopleClick = async () => {
  console.log('发起视频');
  const res = await getLocalStream();
  console.log(res);
  localStream.value = res;
  store.socket?.emit('callRemote', roomId);
};

const receivePeopleClick = () => {
  console.log('同意视频邀请');
  store.socket?.emit('acceptCall', roomId);
};

const handleModalOk = async () => {
  open.value = false;
  console.log('同意视频邀请');
  store.socket?.emit('acceptCall', roomId);

  peer.value = new RTCPeerConnection();

  const localStreamValue = localStream.value;
  if (localStreamValue) {
    localStreamValue.getTracks().forEach(track => {
      peer.value.addTrack(track, localStreamValue);
    });
  } else {
    console.error('无法获取本地流');
  }

  const offer = await peer.value.createOffer({
    offerToReceiveAudio: 1,
    offerToReceiveVideo: 1
  });
  console.log('offer', offer);

  await peer.value.setLocalDescription(offer);

  store.socket.emit('sendOffer', { offer, roomId });
};

function screenShareClick() {
  console.log(start);
  start();
}

// 获取本地音视频流
const getLocalStream = async () => {
  const stream = await navigator.mediaDevices.getUserMedia({
    audio: true,
    video: true
  });
  video.value.srcObject = stream;
  video.value.play();
  return stream;
}


const sendMediaStream = () => {
  try {
    window.navigator.mediaDevices.getDisplayMedia({ video: true })
      .then(mediaStream => {
        peer.current.call(friendId, mediaStream);
      });
  } catch (e) {
    console.error(e);
    alert('Send failed.');
  }
};
const conn = peer.current.connect(friendId);
conn.on('open', () => {
  console.log('Connected.');
  conn.send({ id, msg: 'Hello, my friend!' });
  sendMediaStream();
});

</script>

<style scoped>
/* 样式 */
</style>
